<template>
  <view class="page">
    <u-navbar @leftClick="navLeftClick" :fixed="false" title="收益提现" placeholder bgColor="#fff"></u-navbar>
    <view class="content">
      <view class="info-item">
        <view><text class="lable">可提现金额：</text>¥ {{ incomeCountInfo.balance / 100 || 0 }}</view>
      </view>
      <view class="info-item">
        <view><text class="lable">本次提现：</text>¥ {{ incomeCountInfo.balance / 100 || 0 }}</view>
      </view>
      <view class="info-item">
        <view><text class="lable">实际到账：</text>¥ {{ incomeCountInfo.balance ? (incomeCountInfo.balance * 0.99 / 100).toFixed(2) : 0 }}</view>
        <view class="u-font-24" style="color: #818181;flex-shrink: 0;">提现手续费1%</view>
      </view>
      <view class="info-item">
        <view class="u-flex">
          <text class="lable">提现方式：</text>
          <u-radio-group
            v-model="type"
            placement="column"
            activeColor="#56CB03"
            size="32rpx"
          >
            <u-radio name="bank">银行卡</u-radio>
          </u-radio-group>
        </view>
      </view>
      <view class="info-item">
        <view class="u-line-1">
          <text class="lable">提现账号：</text>
          {{ bankCardInfo ? `${bankCardInfo.bankName}-${bankCardInfo.bankAccount}` : '暂无银行卡' }}
        </view>
        <view class="u-font-24 u-m-l-10" style="color: #56CB03;flex-shrink: 0;" @click="jumpTo('/pages/my/withdrawAccount')">
          {{ bankCardInfo ? '修改' : '绑定' }}
        </view>
      </view>
      <view class="info-item">
        <view><text class="lable">预留手机号：</text>{{ userInfo.phonenumber }}</view>
      </view>
      <view class="info-item" v-if="isCode">
        <view class="u-flex">
          <text class="lable">短信验证码：</text>
          <input style="width: 300rpx;font-size: 28rpx;" v-model="code" type="number" placeholder="请输入验证码" placeholder-style="color: #818181;" />
        </view>
        <view class="u-font-24 u-m-l-10" style="color: #56CB03;flex-shrink: 0;" @click="sendCode">{{ codeTime != 0 ? `重新获取(${codeTime}s)` :'获取验证码'}}</view>
      </view>
      <view class="info-item" style="border: none;">
        <view class="u-flex">
          <text class="lable">上传发票：</text>
          <u-upload
            :fileList="invoiceList"
            accept='image'
            name="invoiceList"
            :sizeType="['compressed']"
            :maxCount="1"
            @delete="deletePic($event, 'invoiceList')"
            @afterRead="afterRead($event, 'invoiceList')"
            :previewFullImage="true"
          ></u-upload>
        </view>
      </view>
    </view>
    <view class="btn" @click="submit">确认提交</view>
  </view>
</template>

<script>
import { uploadImage, phoneReg } from '@/common/util'
import { getAccountsList, incomeCount, sendRegisterCode, checkWithdrawal, withdrawalRecords } from '@/api/index'
let times = null

export default {
  data() {
    return {
      type: 'bank',
      invoiceList: [],
      bankCardInfo: null,
      incomeCountInfo: {},
      userInfo: {},
      code: '',
      codeTime: 0,
      isCode: false,
    };
  },
  onLoad() {
    this.userInfo = uni.getStorageSync('userInfo')
    this.getIncomeCount()
  },
  onShow() {
    this.getCardForm()
  },
  methods: {
    sendCode() {
      const that = this
      if(that.codeTime != 0) {
        return
      }
      if(times) {
        clearInterval(times)
        times = null
      }
      if(!phoneReg(that.userInfo.phonenumber)) {
        return
      }
      sendRegisterCode({phonenumber: that.userInfo.phonenumber}).then(res => {
        uni.showToast({
          icon: 'none',
          title: res.msg
        })
        that.codeTime = 120
        times = setInterval(() => {
          if(that.codeTime == 0) {
            clearInterval(times)
            times = null
            return
          }
          that.codeTime = that.codeTime - 1
        }, 1000)
      })
    },
    getIncomeCount() {
      uni.showLoading({ mask: true })
      incomeCount({ userId: this.userInfo.userId }).then(res => {
        uni.hideLoading()
        this.incomeCountInfo = res.data
      })
    },
    async submit() {
      if(!this.incomeCountInfo.balance) {
        uni.showToast({
          title: '暂无可提现金额',
          icon: 'none'
        })
        return
      }
      if(!this.bankCardInfo) {
        uni.showToast({
          title: '请先绑定银行卡',
          icon: 'none'
        })
        return
      }
      const userInfo = uni.getStorageSync('userInfo')
      uni.showLoading({ mask: true })
      if(this.isCode) {
        this.withdrawFn()
      } else {
        checkWithdrawal({phoneNumber: userInfo.phonenumber}).then(res => {
          if(res.data) {
            this.isCode = false
            this.withdrawFn()
          } else {
            uni.hideLoading()
            this.isCode = true
            uni.showToast({
              title: '请发送验证码',
              icon: 'none'
            })
          }
        })
      }
      
    },
    withdrawFn() {
      const that = this
      if(!this.code && this.isCode) {
        uni.showToast({
          title: '请输入验证码',
          icon: 'none'
        })
        return
      }
      if(this.invoiceList.length == 0) {
        uni.showToast({
          title: '请上传发票',
          icon: 'none'
        })
        return
      }
      
      uni.showLoading({ mask: true })
      const parameter = {
        checkStatus: !this.isCode,
        withdrawalAmount: (this.incomeCountInfo.balance * 0.99).toFixed(0),
        code: this.code,
        invoiceImage: this.invoiceList.map(v => v.url).join(''),
        userId: uni.getStorageSync('userInfo').userId,
        withdrawalMethod: '1',
        phonenumber: this.userInfo.phonenumber,
      }
      withdrawalRecords(parameter).then(res => {
        uni.hideLoading()
        uni.showToast({
          icon: 'none',
          title: `提现成功,请等待打款`
        })
        setTimeout(() => {
          that.jumpTab('/pages/my/my')
        }, 1000)
      })
    },
    getCardForm() {
      uni.showLoading({ mask: true })
      getAccountsList({ userId: uni.getStorageSync('userInfo').userId, orderByColumn: 'create_time', isAsc: 'desc' }).then(res => {
        uni.hideLoading()
        if(res.rows.length) {
          this.bankCardInfo = res.rows[0]
        } else {
          this.bankCardInfo = null
        }
      })
    },
    deletePic(event, name, index=-1) {
      if(index > -1) {
        const info = this[name][index]
        info[event.name].splice(event.index, 1)
        this.$set(this[name], index, info)
        return
      }
      this[name][event.name].splice(event.index, 1);
    },
    // 新增图片
    async afterRead(event, name, index=-1) {
      let lists = [].concat(event.file);
      for (let i = 0; i < lists.length; i++) {
        const res = await uploadImage(lists[0]);
        if(res.code != 200) {
          return
        }
        if(index > -1) {
          const info = {
            status: "success",
            id: res.data.url,
            img: res.data.url,
            type: event.name,
            url: res.data.url
          }
          this.$set(this[name], index, info)
          return
        } else {
          const img = [
            {
              status: "success",
              id: res.data.url,
              img: res.data.url,
              type: event.name,
              url: res.data.url
            }
          ]
          this[name] = img
        }
      }
    },
  },
  beforeDestroy() {
    if(times) {
      clearInterval(times)
      times = null
      this.codeTime = 0
    }
  },
};
</script>

<style lang="scss" scoped>
.page {
  width: 750rpx;
  min-height: 100vh;
  background-color: #F5F5F5;
  padding-bottom: 80rpx;
  position: relative;
  .content {
    width: 702rpx;
    padding: 0 22rpx 16rpx;
    background-color: #fff;
    border-radius: 12rpx;
    margin: 12rpx auto 120rpx;
    .info-item {
      font-size: 28rpx;
      color: #000000;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 30rpx 0;
      border-bottom: 1rpx solid #E1E1E1;
      .lable {
        width: 168rpx;
        margin-right: 8rpx;
      }
    }
  }
  .btn {
    width: 440rpx;
    height: 90rpx;
    line-height: 90rpx;
    text-align: center;
    background: #56CB03;
    border-radius: 200rpx 200rpx 200rpx 200rpx;
    border: 2rpx solid #56CB03;
    font-size: 28rpx;
    color: #FFFFFF;
    margin: 0 auto;
  }
}
</style>
